<template>
  <div class="echarts" ref="chart" :style="echartStyle"></div>
</template>
<script lang="ts" setup>
import { ref, reactive, computed, nextTick, onMounted, onBeforeUnmount, watch, markRaw } from 'vue'
import type { PropType } from 'vue'
import * as echarts from 'echarts'

const props = defineProps({
  option: {
    type: Object as PropType<any>,
    default: () => {}
  },
  background: {
    type: String as PropType<string>,
    default: '#fff'
  },
  width: {
    type: String as PropType<string>,
    default: '100%'
  },
  height: {
    type: String as PropType<string>,
    default: '400px'
  }
})

const emit = defineEmits(['update:selectValue'])

const chart = ref(null)
const MyEcharts = ref<any>(null)

const echartStyle = computed(() => {
  return {
    width: props.width,
    height: props.height,
    background: props.background
  }
})

const resizeChart = () => {
  MyEcharts.value && MyEcharts.value.resize()
}
const initCharts = () => {
  MyEcharts.value = markRaw(echarts.init(chart.value))
  /**
   * 此方法适用于所有项目的图表，但是每个配置都需要在父组件传进来，相当于每个图表的配置都需要写一遍，不是特别的省代码，主要是灵活度高
   * echarts的配置项，你可以直接在外边配置好，直接扔进来一个this.option
   */
  MyEcharts.value.clear() //适用于大数据量的切换时图表绘制错误,先清空在重绘
  MyEcharts.value.setOption(props.option, true) //设置为true可以是图表切换数据时重新渲染

  window.addEventListener('resize', resizeChart)
}

watch(
  () => props.option,
  (newVal, oldVal) => {
    if (MyEcharts.value) {
      if (newVal) {
        MyEcharts.value.setOption(newVal, true)
      } else {
        MyEcharts.value.setOption(oldVal, true)
      }
    } else {
      initCharts()
    }
  },
  { deep: true }
)

onBeforeUnmount(() => {
  // 销毁图表
  MyEcharts.value.dispose()
  // 移除窗口大小变化监听
  window.removeEventListener('resize', resizeChart)
})
onMounted(() => {
  initCharts()
})
</script>
<style lang="less" scoped>
.echarts {
  background-color: #fff;
}
</style>
